<?php
// 连接数据库检查用户是否有下级用户
require_once 'api/inc/config.php';

// 用户信息
$username = '李伟';
$real_name = '李伟';

// config.php已经创建了$conn连接，直接使用即可
try {
    // 1. 先根据用户名和真实姓名获取用户ID
    $stmt = $conn->prepare("SELECT id, is_sub FROM users WHERE username = :username AND real_name = :real_name");
    $stmt->execute([':username' => $username, ':real_name' => $real_name]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        echo "未找到用户：$username<br>";
        exit;
    }
    
    $user_id = $user['id'];
    $is_sub = $user['is_sub'];
    
    echo "找到用户：$username (ID: $user_id, is_sub: $is_sub)<br>";
    
    // 2. 检查是否有下级用户（superior_id = 当前用户ID 且 is_sub = 1） - 使用正确的字段
    $stmt = $conn->prepare("SELECT id, username, real_name, position, sub_mobile FROM users WHERE superior_id = :user_id AND is_sub = 1");
    $stmt->execute([':user_id' => $user_id]);
    $subordinates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($subordinates) > 0) {
        echo "<br>用户有以下下级用户：<br>";
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>ID</th><th>用户名</th><th>真实姓名</th><th>职位</th><th>手机号</th></tr>";
        foreach ($subordinates as $subordinate) {
            echo "<tr>";
            echo "<td>".$subordinate['id']."</td>";
            echo "<td>".$subordinate['username']."</td>";
            echo "<td>".$subordinate['real_name']."</td>";
            echo "<td>".$subordinate['position']."</td>";
            echo "<td>".($subordinate['sub_mobile'] ?: '无')."</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<br>该用户没有下级用户。";
    }
    
    // 3. 额外检查users表中是否存在superior_id字段
    $stmt = $conn->prepare("SHOW COLUMNS FROM users LIKE 'superior_id'");
    $stmt->execute();
    $columnExists = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "<br><br>数据库检查结果：";
    if ($columnExists) {
        echo "users表中存在superior_id字段";
    } else {
        echo "users表中不存在superior_id字段";
    }
    
    // 4. 同时检查是否有parent_user_id字段
    $stmt = $conn->prepare("SHOW COLUMNS FROM users LIKE 'parent_user_id'");
    $stmt->execute();
    $columnExists = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "<br>";
    if ($columnExists) {
        echo "users表中存在parent_user_id字段";
    } else {
        echo "users表中不存在parent_user_id字段";
    }
    
} catch(PDOException $e) {
    echo "数据库操作失败: " . $e->getMessage();
}